import React from 'react';


class Commonts extends React.Component {
    state = {
        commonts: [
            {id: 1, name: 'Jack', content: '我是一楼'},
            {id: 2, name: 'Mike', content: '我是二楼'},
            {id: 3, name: 'Tom', content: '我是三楼'},
        ],
        userName: '',
        userContent: '',
    };

    renderList() {
        const { commonts } = this.state;
        if(commonts.length === 0) {
            return <div>暂无评论，快去评论吧！</div>
        }

        /**
         * 这里不能用map( item => {}) 否则会渲染不出内容
         * 原因：在箭头函数中使用{}时，它会创建一个需要显式语句的代码块return 只需将{}更改为()，就会发生隐式返回
         */

        return(
            <ul>
                {commonts.map( item => (
                    <li key={item.id}>
                        <h3>评论人：{item.name}</h3>
                        <p>评论内容：{item.content}</p>
                    </li>
                ))}
            </ul>
        )
    };

    handleForm = e => {
        const { name, value } = e.target;

        this.setState({
            [name]: value,
        })
    }

    addCommons = () => {
        const { userName, userContent, commonts } = this.state;

        if(userName.trim() === '' || userContent.trim() === '') {
            alert('请输入评论人与评论内容');
            return;
        }

        const newCommonts = [...commonts, {id: Math.random(), name: userName, content: userContent}];

        this.setState({
            commonts: newCommonts,
            userName: '',
            userContent: '',
        })
    }

    render() {
        const { userName, userContent } = this.state;

        return (
            <div>
                <input type="text" placeholder="评论人" value={userName} name="userName" onChange={this.handleForm} /><br />
                <textarea
                    cols="30"
                    rows="10"
                    placeholder="评论内容"
                    value={userContent}
                    name="userContent"
                    onChange={this.handleForm}
                    /><br />
                <button onClick={this.addCommons}>发表评论</button><br />
                {this.renderList()}
            </div>
        );
    }
}

export default Commonts;